package apii.server;

import java.sql.*;
import java.util.*;

import org.h2.jdbcx.*;

import apii.algorithm.tokenizer.*;
import apii.algorithm.tokenizer.Tokenizer.*;

/**
 * <b>Note:</b> Thread SAFE.
 * <p>
 * <b>Note:</b> Doesn't create threads.
 * 
 * @author Alex
 * 
 */
public class ServerThings {
	private static ServerThings things = null;

	public static synchronized ServerThings getThings() {
		if (things == null) {
			things = new ServerThings();
		}
		return things;
	}

	private final JdbcConnectionPool cp;

	public Connection getConnection() throws SQLException {
		Connection c = cp.getConnection();
		try {
			c.setAutoCommit(false);
			try (Statement st = c.createStatement()) {
				st.execute("set schema apii");
			}
			return c;
		} catch (SQLException e) {
			c.close();
			throw e;
		}
	}

	public List<? extends Tokenizer> getTokenizers() {
		return Collections.unmodifiableList(Arrays.asList(new Tokenizer() {

			@Override
			public Token[] parse(String code) throws MalformedCodeException {
				return null;
			}
		}));
	}

	private ServerThings() {
		cp = JdbcConnectionPool.create("jdbc:h2:~/apiidb/apiidb;MVCC=TRUE", "sa", "");
	}

	void finish() {
		cp.dispose();
	}
}
